<template>
    <div class="user-views">
        <el-card class="user-views-card">
            <template #header>
                <div class="card-header">
                    <span>游戏账号</span>
                    <div class="header-actions">
                        <el-button type="primary" size="small" @click="showQueryDialog = true"> 自主查询 </el-button>
                        <span class="right-title">我的游戏账号列表</span>
                    </div>
                </div>
            </template>

            <!-- 搜索和排序区域 -->
            <div class="search-toolbar">
                <div class="search-form">
                    <div class="form-item">
                        <span class="form-label">等级筛选：</span>
                        <el-select v-model="searchForm.select" placeholder="全部等级" clearable @change="handleSearch" style="width: 140px">
                            <el-option label="将军及以下" value="opt0" />
                            <el-option label="上将军" value="opt1" />
                            <el-option label="国护军" value="opt2" />
                            <el-option label="国都护" value="opt3" />
                            <el-option label="斧头帮" value="opt4" />
                        </el-select>
                    </div>

                    <div class="form-item">
                        <span class="form-label">排序字段：</span>
                        <el-select v-model="searchForm.sortField" @change="handleSearch" style="width: 120px">
                            <el-option label="创建时间" value="create_time" />
                            <el-option label="更新时间" value="update_time" />
                            <el-option label="账号ID" value="id" />
                            <el-option label="用户名" value="username" />
                        </el-select>
                    </div>

                    <div class="form-item">
                        <span class="form-label">排序方式：</span>
                        <el-radio-group v-model="searchForm.sortOrder" @change="handleSearch">
                            <el-radio-button label="desc">降序</el-radio-button>
                            <el-radio-button label="asc">升序</el-radio-button>
                        </el-radio-group>
                    </div>

                    <div class="form-item">
                        <el-button @click="resetSearch" type="default">重置筛选</el-button>
                    </div>
                </div>

                <div class="search-stats" v-if="total > 0">
                    <span class="stats-text">共找到 {{ total }} 个账号</span>
                    <span class="stats-filter" v-if="searchForm.select"> （已筛选：{{ getSelectLabel(searchForm.select) }}） </span>
                </div>
            </div>

            <!-- 账号列表 -->
            <div class="log-list">
                <div v-for="(item, index) in logList" :key="index" class="log-item">
                    <div class="log-header">
                        <div class="log-left">
                            <el-image
                                class="game-image"
                                :src="fullUrl(item.image ? item.image : '/static/images/avatar.png')"
                                :preview-src-list="[fullUrl(item.image ? item.image : '/static/images/avatar.png')]"
                                fit="cover"
                                hide-on-click-modal
                                preview-teleported
                                alt="游戏图片"
                            />
                            <div class="log-info">
                                <div class="log-username">
                                    <span class="username-label">账号：</span>
                                    <span class="username-text">{{ item.username }}</span>
                                    <el-button
                                        link
                                        type="primary"
                                        size="small"
                                        @click="copyText(item.username, '账号')"
                                        :loading="item.copyUsernameLoading"
                                        class="copy-btn"
                                    >
                                        <el-icon><CopyDocument /></el-icon>
                                    </el-button>
                                    <el-button
                                        link
                                        type="primary"
                                        @click="querySingleUsername(item.username)"
                                        :loading="item.loading"
                                        class="query-btn"
                                    >
                                        查询昵称
                                    </el-button>
                                    <el-tag v-if="item.nickname" size="small" type="success" class="nickname-tag">
                                        {{ item.nickname }}
                                    </el-tag>
                                    <el-tag v-else-if="item.nickname === ''" size="small" type="info" class="nickname-tag"> 无昵称 </el-tag>
                                </div>
                                <div class="log-password">
                                    <span class="password-label">密码：</span>
                                    <span v-if="item.showPassword" class="password-text">{{ item.password }}</span>
                                    <span v-else class="password-mask">••••••••</span>
                                    <el-button link type="primary" size="small" @click="togglePassword(item)" class="toggle-btn">
                                        {{ item.showPassword ? '隐藏' : '显示' }}
                                    </el-button>
                                    <el-button
                                        v-if="item.showPassword"
                                        link
                                        type="primary"
                                        size="small"
                                        @click="copyText(item.password, '密码')"
                                        :loading="item.copyPasswordLoading"
                                        class="copy-btn"
                                    >
                                        <el-icon><CopyDocument /></el-icon>
                                    </el-button>
                                </div>
                                <div class="log-select">
                                    <span class="select-label">等级：</span>
                                    <el-tag :type="getSelectTagType(item.select)" size="small">
                                        {{ getSelectLabel(item.select) }}
                                    </el-tag>
                                </div>
                            </div>
                        </div>
                        <el-tag :type="item.switch === 1 ? 'success' : 'danger'" size="small">
                            {{ item.switch === 1 ? '可用' : '不可用' }}
                        </el-tag>
                    </div>
                    <div class="log-content">
                        <div class="log-remark" v-if="item.remark">
                            <el-icon><Comment /></el-icon>
                            备注：{{ item.remark }}
                        </div>
                    </div>
                    <div class="log-footer-info">
                        <div class="log-id">
                            <el-icon><Document /></el-icon>
                            ID：{{ item.id }}
                            <el-button link type="primary" size="small" @click="copyText(item.id, 'ID')" class="copy-btn">
                                <el-icon><CopyDocument /></el-icon>
                            </el-button>
                        </div>
                        <div class="log-change-time">
                            <span class="time-item">
                                <el-icon><Clock /></el-icon>
                                创建：{{ timeFormat(item.create_time) }}
                            </span>
                            <span class="time-item">
                                <el-icon><Refresh /></el-icon>
                                更新：{{ timeFormat(item.update_time) }}
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 分页 -->
            <div class="log-footer" v-if="total > 0">
                <el-pagination
                    v-model:current-page="queryParams.page"
                    v-model:page-size="queryParams.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>

            <!-- 空状态 -->
            <el-empty v-if="logList.length === 0 && !loading" :description="emptyDescription" />

            <!-- 加载状态 -->
            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
            </div>
        </el-card>

        <!-- 自主查询对话框 -->
        <el-dialog v-model="showQueryDialog" title="自主查询玩家信息" width="500px" :before-close="handleCloseDialog">
            <el-form :model="queryForm" label-width="80px">
                <el-form-item label="用户名" required>
                    <el-input v-model="queryForm.username" placeholder="请输入要查询的游戏账号" clearable @keyup.enter="handleQuery">
                        <template #append>
                            <el-button @click="copyText(queryForm.username, '用户名')" :disabled="!queryForm.username" title="复制用户名">
                                <el-icon><CopyDocument /></el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>

            <!-- 查询结果 -->
            <div v-if="queryResult" class="query-result">
                <el-divider>查询结果</el-divider>
                <div class="result-item">
                    <strong>用户名：</strong>
                    <span class="result-text">{{ queryResult.username }}</span>
                    <el-button link type="primary" size="small" @click="copyText(queryResult.username, '用户名')" class="copy-btn">
                        <el-icon><CopyDocument /></el-icon>
                    </el-button>
                </div>
                <div class="result-item">
                    <strong>昵称：</strong>
                    <el-tag :type="queryResult.nickname ? 'success' : 'info'">
                        {{ queryResult.nickname || '无昵称' }}
                    </el-tag>
                    <el-button
                        v-if="queryResult.nickname"
                        link
                        type="primary"
                        size="small"
                        @click="copyText(queryResult.nickname, '昵称')"
                        class="copy-btn"
                    >
                        <el-icon><CopyDocument /></el-icon>
                    </el-button>
                </div>
                <div v-if="queryResult.trace_id" class="result-item">
                    <strong>追踪ID：</strong>
                    <span class="result-text">{{ queryResult.trace_id }}</span>
                    <el-button link type="primary" size="small" @click="copyText(queryResult.trace_id, '追踪ID')" class="copy-btn">
                        <el-icon><CopyDocument /></el-icon>
                    </el-button>
                </div>
            </div>

            <template #footer>
                <el-button @click="showQueryDialog = false">取消</el-button>
                <el-button type="primary" @click="handleQuery" :loading="queryLoading"> 查询 </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref, computed } from 'vue'
import { getGameLog, getPlayerNickname, getBatchNicknames, queryPlayerInfo } from '/@/api/frontend/user/index'
import { timeFormat, fullUrl } from '/@/utils/common'
import { ElMessage } from 'element-plus'
import { CopyDocument, Comment, Document, Clock, Refresh } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const total = ref(0)
const logList = ref<any[]>([])
const showQueryDialog = ref(false)
const queryLoading = ref(false)
const queryResult = ref<any>(null)

const queryParams = reactive({
    page: 1,
    pageSize: 10,
})

const searchForm = reactive({
    select: '', // 等级筛选
    sortField: 'create_time', // 排序字段
    sortOrder: 'desc', // 排序方式
})

const queryForm = reactive({
    username: '',
})

// 计算空状态描述
const emptyDescription = computed(() => {
    if (searchForm.select) {
        return `暂无${getSelectLabel(searchForm.select)}的账号`
    }
    return '暂无游戏账号'
})

// select字段映射
const selectOptions = {
    opt0: '将军及以下',
    opt1: '上将军',
    opt2: '国护军',
    opt3: '国都护',
    opt4: '斧头帮',
}

const selectTagTypes = {
    opt0: 'info',
    opt1: 'primary',
    opt2: 'warning',
    opt3: 'success',
}

// 搜索处理
const handleSearch = () => {
    console.log('搜索条件:', searchForm)
    queryParams.page = 1 // 搜索时重置到第一页
    fetchGameLog()
}

// 重置搜索
const resetSearch = () => {
    searchForm.select = ''
    searchForm.sortField = 'create_time'
    searchForm.sortOrder = 'desc'
    queryParams.page = 1
    fetchGameLog()
}

// 复制文本到剪贴板
const copyText = async (text: string, type: string) => {
    try {
        // 设置加载状态
        const itemIndex = logList.value.findIndex((item) => item.username === text || item.password === text || item.id === text)
        if (itemIndex !== -1) {
            if (text === logList.value[itemIndex].username) {
                logList.value[itemIndex].copyUsernameLoading = true
            } else if (text === logList.value[itemIndex].password) {
                logList.value[itemIndex].copyPasswordLoading = true
            }
        }

        // 使用现代 Clipboard API
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(text)
        } else {
            // 降级方案
            const textArea = document.createElement('textarea')
            textArea.value = text
            textArea.style.position = 'fixed'
            textArea.style.left = '-999999px'
            textArea.style.top = '-999999px'
            document.body.appendChild(textArea)
            textArea.focus()
            textArea.select()
            document.execCommand('copy')
            textArea.remove()
        }

        ElMessage.success(`${type}复制成功`)
    } catch (error) {
        console.error('复制失败:', error)
        ElMessage.error(`${type}复制失败`)
    } finally {
        // 重置加载状态
        const itemIndex = logList.value.findIndex((item) => item.username === text || item.password === text || item.id === text)
        if (itemIndex !== -1) {
            if (text === logList.value[itemIndex].username) {
                setTimeout(() => {
                    logList.value[itemIndex].copyUsernameLoading = false
                }, 500)
            } else if (text === logList.value[itemIndex].password) {
                setTimeout(() => {
                    logList.value[itemIndex].copyPasswordLoading = false
                }, 500)
            }
        }
    }
}

// 获取select字段的显示标签
const getSelectLabel = (selectValue: string) => {
    return selectOptions[selectValue as keyof typeof selectOptions] || selectValue
}

// 获取select字段的标签类型
const getSelectTagType = (selectValue: string) => {
    return selectTagTypes[selectValue as keyof typeof selectTagTypes] || 'info'
}

// 切换密码显示状态
const togglePassword = (item: any) => {
    item.showPassword = !item.showPassword
}

// 获取游戏账号列表
const fetchGameLog = async () => {
    try {
        loading.value = true
        console.log('请求参数:', {
            page: queryParams.page,
            pageSize: queryParams.pageSize,
            select: searchForm.select,
            sortField: searchForm.sortField,
            sortOrder: searchForm.sortOrder,
        })

        const response = await getGameLog(queryParams.page, queryParams.pageSize, searchForm.select, searchForm.sortField, searchForm.sortOrder)

        console.log('API响应:', response)

        if (response && response.code === 1 && response.data) {
            const list = response.data.list || []
            // 初始化数据，添加各种状态字段
            logList.value = list.map((item) => ({
                ...item,
                showPassword: false, // 默认隐藏密码
                loading: false,
                nickname: '', // 初始化昵称
                copyUsernameLoading: false, // 复制用户名加载状态
                copyPasswordLoading: false, // 复制密码加载状态
            }))
            total.value = response.data.total || 0

            // 批量查询当前页所有用户的昵称
            await batchQueryCurrentPage()
        } else {
            logList.value = []
            total.value = 0
            if (response?.msg) {
                ElMessage.warning(response.msg)
            }
        }
    } catch (error) {
        console.error('获取游戏账号失败:', error)
        ElMessage.error('获取游戏账号失败')
        logList.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

// 批量查询当前页所有用户名
const batchQueryCurrentPage = async () => {
    try {
        const usernames = logList.value.map((item) => item.username).filter(Boolean)
        if (usernames.length === 0) return

        const response = await getBatchNicknames(usernames)
        if (response && response.code === 1 && response.data) {
            const nicknames = response.data.nicknames || {}

            // 更新昵称到列表
            logList.value = logList.value.map((item) => ({
                ...item,
                nickname: nicknames[item.username] || '',
                loading: false,
            }))
        }
    } catch (error) {
        console.error('批量查询昵称失败:', error)
        ElMessage.warning('部分昵称查询失败')
    }
}

// 查询单个用户名
const querySingleUsername = async (username: string) => {
    try {
        // 设置加载状态
        const itemIndex = logList.value.findIndex((item) => item.username === username)
        if (itemIndex !== -1) {
            logList.value[itemIndex].loading = true
        }

        const response = await getPlayerNickname(username)
        if (response && response.code === 1 && response.data) {
            const nickname = response.data.nickname

            // 更新昵称
            if (itemIndex !== -1) {
                logList.value[itemIndex].nickname = nickname
                logList.value[itemIndex].loading = false
            }

            ElMessage.success(`用户 ${username} 的昵称: ${nickname || '无昵称'}`)
        } else {
            ElMessage.error('查询昵称失败')
        }
    } catch (error) {
        console.error('查询昵称失败:', error)
        ElMessage.error('查询昵称失败')

        // 重置加载状态
        const itemIndex = logList.value.findIndex((item) => item.username === username)
        if (itemIndex !== -1) {
            logList.value[itemIndex].loading = false
        }
    }
}

// 自主查询
const handleQuery = async () => {
    if (!queryForm.username.trim()) {
        ElMessage.warning('请输入用户名')
        return
    }

    try {
        queryLoading.value = true
        const response = await queryPlayerInfo(queryForm.username.trim())

        if (response && response.code === 1 && response.data) {
            queryResult.value = response.data
            ElMessage.success('查询成功')
        } else {
            ElMessage.error(response?.msg || '查询失败')
        }
    } catch (error) {
        console.error('自主查询失败:', error)
        ElMessage.error('查询失败')
    } finally {
        queryLoading.value = false
    }
}

// 关闭对话框
const handleCloseDialog = () => {
    showQueryDialog.value = false
    queryForm.username = ''
    queryResult.value = null
}

// 分页大小改变
const handleSizeChange = (newSize: number) => {
    queryParams.pageSize = newSize
    queryParams.page = 1
    fetchGameLog()
}

// 当前页改变
const handleCurrentChange = (newPage: number) => {
    queryParams.page = newPage
    fetchGameLog()
}

// 初始化
onMounted(() => {
    fetchGameLog()
})
</script>

<style scoped lang="scss">
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

.user-views-card :deep(.el-card__body) {
    padding-top: 0;
}

.right-title {
    color: var(--el-text-color-secondary);
    font-size: 14px;
}

.search-toolbar {
    padding: 16px 0;
    border-bottom: 1px solid var(--el-border-color-light);
    margin-bottom: 16px;
}

.search-form {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
    margin-bottom: 12px;
}

.form-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-label {
    color: var(--el-text-color-regular);
    font-size: 14px;
    white-space: nowrap;
}

.search-stats {
    padding: 8px 0;
    border-top: 1px dashed var(--el-border-color-lighter);
}

.stats-text {
    color: var(--el-text-color-primary);
    font-size: 14px;
}

.stats-filter {
    color: var(--el-color-primary);
    font-size: 13px;
}

.log-item {
    border-bottom: 1px solid var(--el-border-color-light);
    padding: 16px 0;

    &:last-child {
        border-bottom: none;
    }
}

.log-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
}

.log-left {
    display: flex;
    align-items: flex-start;
    gap: 12px;
}

.game-image {
    width: 60px;
    height: 60px;
    border-radius: 8px;
    object-fit: cover;
    border: 1px solid var(--el-border-color-light);
    cursor: pointer;
    flex-shrink: 0;
}

.log-info {
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-width: 0;
}

.log-username {
    display: flex;
    align-items: center;
    gap: 6px;
    flex-wrap: wrap;
}

.username-label {
    color: var(--el-text-color-regular);
    font-size: 14px;
    white-space: nowrap;
}

.username-text {
    font-family: monospace;
    background: var(--el-fill-color-light);
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 14px;
}

.nickname-tag {
    margin-left: 4px;
}

.log-password {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: var(--el-text-color-regular);
    flex-wrap: wrap;
}

.password-label {
    color: var(--el-text-color-regular);
    white-space: nowrap;
}

.password-text {
    font-family: monospace;
    background: var(--el-fill-color-light);
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 14px;
}

.password-mask {
    font-family: monospace;
    letter-spacing: 2px;
    background: var(--el-fill-color-light);
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 14px;
}

.log-select {
    display: flex;
    align-items: center;
    gap: 8px;
}

.select-label {
    color: var(--el-text-color-regular);
    font-size: 14px;
    white-space: nowrap;
}

.copy-btn {
    padding: 2px 4px;
    min-height: auto;

    .el-icon {
        font-size: 12px;
    }
}

.query-btn {
    padding: 2px 8px;
    min-height: auto;
    font-size: 12px;
    height: 24px;
}

.toggle-btn {
    padding: 2px 8px;
    min-height: auto;
    font-size: 12px;
    height: 24px;
}

.log-content {
    margin-bottom: 12px;
}

.log-remark {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: var(--el-text-color-secondary);
    font-style: italic;
    background: var(--el-fill-color-light);
    padding: 6px 12px;
    border-radius: 6px;
    display: inline-flex;

    .el-icon {
        font-size: 14px;
    }
}

.log-footer-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: var(--el-text-color-secondary);
}

.log-id {
    display: flex;
    align-items: center;
    gap: 4px;
    font-family: monospace;
    background: var(--el-fill-color-light);
    padding: 4px 8px;
    border-radius: 4px;

    .el-icon {
        font-size: 12px;
    }
}

.log-change-time {
    display: flex;
    gap: 16px;
}

.time-item {
    display: flex;
    align-items: center;
    gap: 4px;

    .el-icon {
        font-size: 12px;
    }
}

.log-footer {
    padding-top: 20px;
    display: flex;
    justify-content: center;
}

.loading-container {
    padding: 20px 0;
}

.query-result {
    margin-top: 16px;
}

.result-item {
    margin: 8px 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.result-text {
    font-family: monospace;
    background: var(--el-fill-color-light);
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 14px;
}

:deep(.el-pagination) {
    justify-content: center;
}

@media (max-width: 768px) {
    .search-form {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .form-item {
        width: 100%;
        justify-content: space-between;
    }

    .log-header {
        flex-direction: column;
        gap: 12px;
    }

    .log-footer-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .game-image {
        width: 50px;
        height: 50px;
    }

    .log-username {
        flex-wrap: wrap;
    }

    .log-password {
        flex-wrap: wrap;
    }

    .log-change-time {
        flex-direction: column;
        gap: 4px;
    }

    .search-stats {
        text-align: center;
    }
}
</style>
